package com.xy.smartsms.presenter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.xy.smartsms.data.ISmsPlugin;
import com.xy.smartsms.facade.SmsProcessFacade;
import com.xy.smartsms.manager.PublicInfoManager;
import com.xy.smartsms.util.CommonUtils;
import com.xy.smartsms.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.ui.manager.CardViewFactory;
import cn.cmcc.online.smsapi.ui.manager.IBaseView;


/**
 * Created by admin on 2017/1/13.
 */

public class BubblePresenterImpl extends BubblePresenter {
    private static final String TAG = "BubblePresenterImpl";
    private static final String BUBBLE_MODE = "bubble_display_mode";

    private Handler mHandler = null;

    public BubblePresenterImpl(Context context) {
        super(context);
        Log.i(TAG, "BubblePresenterImpl: ");
        mHandler = new Handler(context.getMainLooper());
    }

    @Override
    public int getBubbleMode() {
        try {
            if (mRichBubbleData == null || !mRichBubbleData.has(BUBBLE_MODE)) {
                return BUBBLE_MODE_RICH;
            }

            return mRichBubbleData.getInt(BUBBLE_MODE);
        } catch (Throwable t) {
            Log.e(TAG, "getBubbleMode", t);
        }

        return BUBBLE_MODE_RICH;
    }

    @Override
    public void setBubbleMode(int mode) {
        try {
            if (mRichBubbleData == null) {
                return;
            }

            mRichBubbleData.put(BUBBLE_MODE, mode);
        } catch (Throwable t) {
            Log.e(TAG, "setBubbleMode", t);
        }
    }

    @Override
    public void load(int type) {
        switch (type) {
            case TYPE_RICH:
                loadRich();
                break;

            case TYPE_SIMPLE:
                loadSimple();
                break;

            case TYPE_FEATURE:
                loadFeature();
                break;

            case TYPE_SENSITIVE:
                loadSensitive();
                break;

            default:
                break;
        }
    }

    private void updateFeatureStringSafe() {
        Log.d(TAG, "updateFeatureString: data=" + mFeatureData);
    }

    private void updateFeatureString() {
        if (CommonUtils.isMainThread()) {
            updateFeatureStringSafe();
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateFeatureStringSafe();
                }
            });
        }
    }

    private void updateSimpleViewSafe() {
        if (vista == null) {
            return;
        }

    }

    private void updateSimpleView() {
        if (CommonUtils.isMainThread()) {
            updateSimpleViewSafe();
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateSimpleViewSafe();
                }
            });
        }
    }

    private void updateRichViewSafe() {
        if (vista == null) {
            return;
        }

        Log.d(TAG, "updateRichView: data=" + mRichBubbleData);
        if (mRichBubbleData == null) {
            vista.showRichBubble(null);
            return;
        }

        int type = mRichBubbleData.optInt("card_type");
        IBaseView baseView = CardViewFactory.getInstance().getCacheBaseView(type, mAdapterView);
        baseView.bind(mContext, mRichBubbleData);
        View view = baseView.getView();
        vista.showRichBubble(view);
    }

    private void updateRichView() {
        if (CommonUtils.isMainThread()) {
            updateRichViewSafe();
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateRichViewSafe();
                }
            });
        }
    }

    private void updateSensitiveViewSafe() {
        if (vista == null || mSensitiveData == null) {
            return;
        }

    }

    private void updateSensitiveView() {
        if (CommonUtils.isMainThread()) {
            updateSensitiveViewSafe();
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateSensitiveViewSafe();
                }
            });
        }
    }

    private void cacheRichBubbleData(JSONObject data) {
        if (data == null) {
            return;
        }

        mRichBubbleData = data;
        putBubbleDataToCache(data);
    }

    private void callbackRichBubbleData(int status, final JSONObject data) {
        if (status == ISmsPlugin.STATUS_SUCCESS) {
            final String logo = data.optString("card_logo");
            if (TextUtils.isEmpty(logo)) {
                PublicInfoManager.getInstance().loadPublicInfo(mMessageItem.getPhone(), new PublicInfoManager.OnPublicInfoListener() {
                    @Override
                    public void onPublicInfo(String phone, String name, BitmapDrawable drawable, JSONObject obj) {
                        if (obj != null) {
                            try {
                                String logoc = obj.optString("logoc");
                                if (!TextUtils.isEmpty(logoc)) {
                                    if (drawable == null) {
                                        Log.i(TAG, "onPublicInfo: logo not ready:" + logoc);
                                        return;
                                    }

                                    data.put("card_logo", NetUtil.BIZPORT_DOWN_URL + logoc);

                                    String color = obj.optString("backColor");
                                    if (!TextUtils.isEmpty(color)) {
                                        data.put("title_color", color);
                                    }
                                }

                                cacheRichBubbleData(data);
                            } catch (Throwable t) {
                                Log.e(TAG, "onPublicInfo: ", t);
                            }
                        }
                    }
                }, true);
            } else {
                cacheRichBubbleData(data);
            }
        }

        updateRichView();
    }

    private void callbackSimpleBubbleData(int status, JSONObject data) {
    }

    private void callbackFeatureData(int status, JSONObject data) {
        if (status == ISmsPlugin.STATUS_SUCCESS) {
            mFeatureData = data;
        }

        updateFeatureString();
    }

    private void callbackSensitiveData(int status, JSONObject data) {
        if (status == ISmsPlugin.STATUS_SUCCESS) {
            mSensitiveData = data;
        }

        updateSensitiveView();
    }

    private boolean isActivityFinish() {
        if (mContext != null) {
            Activity activity = (Activity) mContext;
            if (activity.isFinishing()) {
                return true;
            }
        }

        return false;
    }

    private SmsProcessFacade.ISmsProcessCallback mProcessCallback = new SmsProcessFacade.ISmsProcessCallback() {
        @Override
        public void onCard(int status, int type, String cacheKey, JSONObject data) {
            if (isActivityFinish() ||
                    !cacheKey.equals(getCacheKey())
                    || status != ISmsPlugin.STATUS_SUCCESS
                    || data == null) {
                return;
            }

            switch (type) {
                case ISmsPlugin.TYPE_RICH:
                    callbackRichBubbleData(status, data);
                    break;

                case ISmsPlugin.TYPE_SIMPLE:
                    callbackSimpleBubbleData(status, data);
                    break;

                case ISmsPlugin.TYPE_FEATURE:
                    callbackFeatureData(status, data);
                    break;

                case ISmsPlugin.TYPE_SENSITIVE:
                    callbackSensitiveData(status, data);
                    break;
            }
        }
    };

    private void loadByFlag(int flag) {
        Log.i(TAG, "loadByFlag: flag=" + flag);
        SmsProcessFacade.getInstance().parseCard(flag, mMessageItem, mProcessCallback);
    }

    private void loadFeature() {
        if (mFeatureData != null) {
            updateFeatureString();
            return;
        }

        loadByFlag(ISmsPlugin.TYPE_FEATURE);
    }

    private void loadSimple() {
        if (mSimpleBubbleData == null && mRichBubbleData != null) {
            try {
                String adaction = mRichBubbleData.optString("NEW_ADACTION");
                if (!TextUtils.isEmpty(adaction)) {
                    mSimpleBubbleData = new JSONArray(adaction);
                }
            } catch (Throwable t) {
                Log.e(TAG, "loadSimple", t);
            }
        }

        if (mSimpleBubbleData != null) {
            updateSimpleView();
            return;
        } else {
            // in order to load default in time
            updateSimpleView();
        }

        loadByFlag(ISmsPlugin.TYPE_SIMPLE);
    }

    private void loadRich() {
        if (mRichBubbleData != null) {
            updateRichView();
            return;
        } else {
            // in order to load default in time
            updateRichView();
        }

        loadByFlag(ISmsPlugin.TYPE_RICH);
    }

    private void loadSensitive() {
        if (mSensitiveData != null) {
            updateSensitiveView();
            return;
        }

        loadByFlag(ISmsPlugin.TYPE_SENSITIVE);
    }
}
